import React, { useState, useEffect } from "react";
import {
  Container, CircularProgress, Typography,
  FormControl, InputLabel, MenuItem, Select
} from "@mui/material";
import { styled } from "@mui/material/styles";
import QuizPage from "../components/Quiz";
import QuizResult from "../components/QuizResult";
import {quizService} from '../service/quizService';
import { textbookService } from '../service/textbookService';
import storage from '../utils/storage';
import quizHistoryService from '../service/quizHistoryService';

// 自定义内容区域样式
const ContentContainer = styled(Container)(({ theme }) => ({
  paddingTop: theme.spacing(10),
  paddingBottom: theme.spacing(10),
  minHeight: "calc(100vh - 112px)",
  display: "flex",
  flexDirection: "column",
}));


export const totalQuizAmount = 5;

const GoPage = () => {
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [currentQuestionNumber, setCurrentQuestionNumber] = useState(1);
  const [currentQuiz, setCurrentQuiz] = useState({});
  const [userAnswers, setUserAnswers] = useState({});
  const [showAnswer, setShowAnswer] = useState(false);
  const [isQuizFinished, setIsQuizFinished] = useState(false);
  const [quizData, setQuizData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [loadingChapter, setLoadingChapter] = useState(true);
  const [chapters, setChapters] = useState([]);
  const [currentChapter, setCurrentChapter] = useState(null);
  const [quizStat, setQuizStat] = useState({});

  useEffect(() => {
    const cc = storage.get('currentChapter');
    if(cc) {
      setCurrentChapter(cc);
    }

    setLoadingChapter(true);
    textbookService.getChapters().then(response => {
      setChapters(response);
      if (!cc && response.length > 0) {
        setCurrentChapter(response[0].chapter_title);
      }
      console.log('Fetched chapters:', response.data)
    }).catch(error => {
      console.error('Error fetching chapters:', error);
    }).finally(() => {
      setLoadingChapter(false);
    }
    );
  }, []);

  const fetchQuizData = async (chapterTitle) => {
    try {
      setLoading(true);
      setQuizData([]);
      const {topQuizzes:quizList, allHistory, quizAmount} = await quizService.getTopQuizzes(chapterTitle, totalQuizAmount);
      setQuizStat({
        quizAmount,
        answeredAmount: allHistory.length
      });
      setQuizData(quizList);
      if(quizList && quizList.length > 0) {
        const initialQuestionIndex = Math.floor(Math.random() * quizList.length);
        setCurrentQuestionIndex(initialQuestionIndex);
        setCurrentQuiz(quizList[initialQuestionIndex]);
      }
      console.log('Fetched quiz data:', quizList);
    } catch (error) {
      console.error('Error fetching quiz data:', error);
    }
    setLoading(false);
  };

  useEffect(() => {
    if (currentChapter) {
      fetchQuizData(currentChapter);
    }
  }, [currentChapter]);


  const handleAnswerChange = async (event) => {
    if (!showAnswer) {
      console.log(currentQuiz);
      userAnswers[currentQuestionIndex] = event.target.value;
      const selectedIndex = parseInt(event.target.value);
      await quizHistoryService.updateHistory(currentQuiz, selectedIndex);
      setUserAnswers(userAnswers);
      handleButtonClick();
    }
  };

  const handleButtonClick = () => {
    if (!showAnswer) {
      setShowAnswer(true);
    } else {
      if (currentQuestionNumber < totalQuizAmount) {
        let nextQuestionIndex;
        do {
          nextQuestionIndex = Math.floor(Math.random() * quizData.length);
        } while (userAnswers[nextQuestionIndex] !== undefined);
        setCurrentQuestionIndex(nextQuestionIndex);
        setShowAnswer(false);
        setCurrentQuestionNumber(currentQuestionNumber + 1);
        setCurrentQuiz(quizData[nextQuestionIndex]);
      } else {
        setIsQuizFinished(true);
      }
    }
  };

  // 重置测验的函数
  const handleRestart = async () => {
    await fetchQuizData(currentChapter);
    const initialQuestionIndex = Math.floor(Math.random() * quizData.length);
    setCurrentQuestionIndex(initialQuestionIndex);
    setCurrentQuiz(quizData[initialQuestionIndex]);
    setUserAnswers({});
    setShowAnswer(false);
    setIsQuizFinished(false);
    setCurrentQuestionNumber(1);
  };

  if (loadingChapter) {
    return (
      <ContentContainer style={{ textAlign: 'center' }}>
        <CircularProgress />
      </ContentContainer>
    );
  }
  return (
    <ContentContainer>
      {isQuizFinished ? (
        <QuizResult userAnswers={userAnswers} quizData={quizData} onRestart={handleRestart} />
      ) : (
        <>
          <FormControl sx={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
            <InputLabel id="chapter-select-label">选择章节</InputLabel>
            <Select
              labelId="chapter-select-label"
              id="chapter-select"
              value={currentChapter}
              label="选择章节"
              onChange={(event) => {
                setCurrentChapter(event.target.value);
                storage.set('currentChapter', event.target.value);
              }}
            >
              {chapters.map((chapter, index) => (
                <MenuItem key={index} value={chapter.chapter_title}>{chapter.chapter_title}</MenuItem>
              ))}
            </Select>
          </FormControl>
          <div style={{ height: 20 }} />
          {(currentChapter && (loading || !currentQuiz)) && (
            <ContentContainer style={{ textAlign: 'center' }}>
              <CircularProgress />
            </ContentContainer>
          ) }
          {/* 无数据时显示提示信息 */}
          {quizData.length === 0 ? (
            <Typography variant="h5" gutterBottom>
              {currentChapter ? '无数据' : '请选择章节'}
            </Typography>
          ) : (
            <QuizPage
              currentQuestionIndex={currentQuestionIndex}
              currentQuestionNumber={currentQuestionNumber}
              currentQuiz={currentQuiz}
              userAnswers={userAnswers}
              showAnswer={showAnswer}
              quizStat={quizStat}
              onAnswerChange={handleAnswerChange}
              onButtonClick={handleButtonClick}
            />
          )
          }

        </>
      )}
    </ContentContainer>
  );
};

export default GoPage;
